package count.negative.quickstarter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;

import com.mobeta.android.dslv.DragSortListView;

public class MainActivity extends Activity {
	private static final String PREFS_NAME = "prefs";
	private static final String LOG_TAG = "QuickStarter";
	private PackageManager pm;
	public static List<ResolveInfo> resolveInfos = Collections.synchronizedList(new ArrayList<ResolveInfo>());
	public static List<String> selectedPackageNames = new ArrayList<String>();
	private ArrayAdapter<ResolveInfo> arrayAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pm = getApplicationContext().getPackageManager();

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		String selPas = settings.getString("selectedPackages", "");
		if (selPas.length() > 0) {
			selectedPackageNames = new ArrayList<String>(Arrays.asList(selPas.split(",")));
			Log.d(LOG_TAG, "load: " + selPas);
		}

		final DragSortListView listview = (DragSortListView) findViewById(R.id.listView);
		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		resolveInfos = pm.queryIntentActivities(mainIntent, 0);

		Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
		int x = 0;
		for (int j = 0; j < selectedPackageNames.size(); j++) {
			String selectedPackageName = selectedPackageNames.get(j);
			for (int i = 0; i < resolveInfos.size(); i++) {
				ResolveInfo info = resolveInfos.get(i);
				// remove ourself to prevent endless loops
				if (info.activityInfo.packageName.equals(getPackageName())) {
					resolveInfos.remove(i);
					i = 0;
				}
				// sort the found packages to get the selected ones first
				if (selectedPackageName.equals(info.activityInfo.packageName)) {
					Collections.swap(resolveInfos, i, x);
					i = x++;
				}
			}
		}

		Log.d(LOG_TAG, "onCreate: " + savedInstanceState);
		if (savedInstanceState == null) {
			startApps();
		}

		arrayAdapter = new IntentAdapter(getApplicationContext(), R.layout.tablerow, resolveInfos);
		listview.setAdapter(arrayAdapter);

		listview.setDropListener(new DragSortListView.DropListener() {
			@Override
			public void drop(int from, int to) {
				if (from != to) {
					//										DragSortListView list = (DragSortListView) findViewById(R.id.listView);
					ResolveInfo item = arrayAdapter.getItem(from);
					arrayAdapter.remove(item);
					arrayAdapter.insert(item, to);

					for (int i = 0; i < selectedPackageNames.size(); i++) {
						String selPan = selectedPackageNames.get(i);
						if (item.activityInfo.packageName.equals(selPan)) {
							int nto = to > selectedPackageNames.size() ? selectedPackageNames.size() - 1 : to;
							Collections.swap(selectedPackageNames, i, nto);
							break;
						}
					}
					//										list.moveCheckState(from, to);
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		startApps();
		return super.onMenuItemSelected(featureId, item);
	}

	private void startApps() {
		for (int i = selectedPackageNames.size() - 1; i >= 0; i--) {
			String selectedPackage = selectedPackageNames.get(i);
			Intent intent = pm.getLaunchIntentForPackage(selectedPackage);
			// could be deinstalled in the meantime
			if (intent != null) {
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setAction(Intent.ACTION_MAIN);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

				startActivityForResult(intent, 0);
			}
		}
	}

	@Override
	protected void onPause() {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		String join = join(selectedPackageNames);
		Log.d(LOG_TAG, "save: " + join);
		editor.putString("selectedPackages", join);
		editor.commit();

		super.onPause();
	}

	private String join(List<String> applicationInfos) {
		StringBuilder sb = new StringBuilder();
		for (String applicationInfo : applicationInfos) {
			sb.append(applicationInfo).append(",");
		}
		return sb.toString();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.d(LOG_TAG, "onSaveInstanceState");
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.d(LOG_TAG, "onRestoreInstanceState");
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onStart() {
		Log.d(LOG_TAG, "onStart");
		super.onStart();
	}

	@Override
	protected void onStop() {
		Log.d(LOG_TAG, "onStop");
		super.onStop();
	}

	@Override
	protected void onRestart() {
		Log.d(LOG_TAG, "onRestart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		Log.d(LOG_TAG, "onResume");
		super.onResume();
	}

}
